package com.poker.monitor.ocr;

import android.graphics.Bitmap;

import org.jetbrains.annotations.NotNull;
import org.json.JSONArray;
import org.json.JSONException;

import okhttp3.*;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.concurrent.TimeUnit;




public class OcrService {
    private static final String OCR_API_URL = "http://192.168.0.103:8080/ocr";
    private final OkHttpClient client;

    public OcrService() {
        client = new OkHttpClient.Builder()
            .connectTimeout(10, TimeUnit.SECONDS)
            .writeTimeout(10, TimeUnit.SECONDS)
            .readTimeout(30, TimeUnit.SECONDS)
            .build();
    }

    public void recognizeText(Bitmap image, OcrCallback callback) {
        // 将Bitmap转换为字节数组
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        image.compress(Bitmap.CompressFormat.JPEG, 100, stream);
        byte[] byteArray = stream.toByteArray();

        // 构建multipart请求
        RequestBody requestBody = new MultipartBody.Builder()
            .setType(MultipartBody.FORM)
            .addFormDataPart("multipartFile", "image.jpg",
                RequestBody.create(MediaType.parse("image/jpeg"), byteArray))
            .build();

        // 发送请求
        Request request = new Request.Builder()
            .url(OCR_API_URL)
            .post(requestBody)
            .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                callback.onFailure(new OcrException(OcrException.ErrorType.NETWORK_ERROR, "网络请求失败: " + e.getMessage()));
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) {
                try (ResponseBody body = response.body()) {
                    if (!response.isSuccessful()) {
                        callback.onFailure(new OcrException(OcrException.ErrorType.API_ERROR, "HTTP错误: " + response.code()));
                        return;
                    }

                    if (body == null) {
                        callback.onFailure(new OcrException(OcrException.ErrorType.INVALID_RESPONSE, "空响应体"));
                        return;
                    }

                    String result = body.string();
                    JSONArray jsonResults = new JSONArray(result);
                    callback.onSuccess(jsonResults);
                } catch (IOException | JSONException e) {
                    callback.onFailure(new OcrException(OcrException.ErrorType.INVALID_RESPONSE, e.getMessage()));
                } catch (Exception e) {
                    callback.onFailure(new OcrException(OcrException.ErrorType.UNKNOWN_ERROR, "未知错误: " + e.getMessage()));
                }
            }
            
        });
        }

    public void setApiUrl(String url) {
        // 用于配置API地址
    }
}